package controller.actions;

import model.controller.*;
import model.controller.UserController.AdministratorController;
import model.controller.UserController.BookmakerController;
import model.controller.UserController.ClientController;
import model.controller.UserController.UserController;
import model.user.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LoginAction implements Action {

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response){
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        Statement stmt = null;
        Connection conn = null;
        ResultSet r =null;

        UserController userController = new UserController();
        User user = new User(login,password);
        try {
            userController.checkIfUserExist(user);
            HttpSession session = request.getSession(true);
            session.setAttribute("user", login);

            if(userController.checkStatus(user).equals("client")) {
                try {
                    session.setAttribute("controller",new ClientController());
                    session.setAttribute("status","client");
                    return "/client.jsp";
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(userController.checkStatus(user).equals("bookmaker")) {
                try {
                    session.setAttribute("controller",new BookmakerController());
                    session.setAttribute("status","bookmaker");
                    return "/bookmaker.jsp";
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(userController.checkStatus(user).equals("administrator")) {
                try {
                    session.setAttribute("controller",new AdministratorController());
                    session.setAttribute("status","administrator");
                    return "administrator.jsp";
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        } catch (ControllerException e) {
            request.setAttribute("errorMessage", e.getMessage());
            return "/error.jsp";
        }
        return null;
    }
}



